import { signApi, queryPageSortApi,basicInformationLastApi,queryPage2Api, studentMHRLastApi, bestResultApi, querySignRecordApi } from '../../api/trainingData'
import { queryOneApi } from '../../api/home'
import store from '../../utils/store';
import tools from '../../tools/tools';
const app = getApp();
Page({
  data: {
    ids: [],
    showChart: false,
    activePeriod: 'week', // 默认“周”高亮
    linesHideCanvas: true,
    today: tools.formatDate(new Date()),
    collapseActiveNames: [0],
    contents: [
      '这是选项一的内容',
      '这是选项二的内容',
      '这是选项三的内容',
      '这是选项四的内容'
    ],
    options: [],
    selectType: 'multi', // 单选模式，可选值：single(单选) multi(多选)
    maxSelect: 4, // 多选模式下的最大选择数量
    chartData: {
      type: 'line',
      xAxis: ['0', '5', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55', '60'],
      xAxisName: '时间（分钟）',
      yAxisName: '次数',
      data: [
        90, 95, 91, 95, 92, 92, 93, 96, 94, 96, 94, 95, 93
      ],
      series: [{
        type: 'line',
        smooth: true,
        lineStyle: {
          color: 'red'
        },
        itemStyle: {
          normal: {
            color: '#5470C6'
          }
        }
      }]
    },
    chartAllData: [],
    calendarData1: {
      show: false,
      minDate: "2024-01-01",
      todos: [],
      date: tools.formatDate(new Date())
    },
    calendarData2: {
      show: false,
      minDate: "2024-01-01",
      todos: [],
      date: ''
    },
    physical: [],
    scoreList: [],
    active: 0,
    chartWidth: 0,
    titleData: [
      {date:'训练日期'},
      {heartRate: '平均心率'},
      {maxHeartReat: '最大心率'},
      {anaerobicThreshold:'无氧阀值'},
      {heart10Rate: '10s心率'},
      {calorie: '卡路里'}
    ],
    tableData: [],
    titleData2: [
      {date: '日期'},
      {value1 :'体重'},
      {value2: '体脂率'},
      {value3: '肌肉量'},
      {value4: '皮下脂肪率'},
      {value5: '骨骼肌率'},
      {value6: '躯干肌肉比率'},
    ],
    tableData2: [],
    dialogShow: false,
    dialogShow2: false,
    activeNames: ['1'],
    monthActive: 1,
    // 训练数据
    baseData: null,
    // 分段心率
    segmentedHeartRate: [],
    colorArr: ["#e70012", "#ffc208", "#f5ff00", "#6cff00", "#01ffc1"],
    dataSource: [
      { name: "无氧爆发", r: ">95%", value: 10, percent: 10, time: "00:10" },
      { name: "无氧乳酸耐受", r: "95%-85%", value: 25, percent: 25, time: "00:25" },
      { name: "混氧阈阀", r: "85%-75%", value: 40, percent: 40, time: "00:40" },
      { name: "有氧耐力", r: "75%-60%", value: 30, percent: 20, time: "00:20" },
      { name: "热身恢复", r: "<60%", value: 50, percent: 5, time: "00:05" },
    ],
    hideCanvas: false,
    groupSelectedCounts: []
  },
  /**
   *    训练事件
   */
  onCollapseChange(event) {
    this.setData({ collapseActiveNames: event.detail });
  },
  // 切换周/月/年
  switchPeriod(e) {
    const { type } = e.currentTarget.dataset;
    this.setData({
      activePeriod: type
    })
  },
  // 训练数据 - 训练记录按钮事件
  goTrainRecords() {
    this.setData({ dialogShow: true });
  },
   // 训练数据 - 日历选择日期
  onDateChange1(e) {
    const {date} = e.detail
    this.setData({
      "calendarData1.show": false,
      "calendarData1.date": date,
      "hideCanvas": false,
      "today": date
    })
    // 基础数据
    this.getbasicInformationLast(date)
    // 训练数据 - 获取心率区间分布接口
    this.getHeartRate(date)
    // 训练数据 - 获取心率区间分布接口
    this.getHeartRateCharts(date)
    // 训练数据 - 心率曲线
    // this.getHeartRateCurveCharts(date)
  },
  // 训练数据 - 选择日期按钮事件
  changetime(e) {
    this.setData({
      "calendarData1.show": true,
      "hideCanvas": true
    })
  },
  // 训练数据 - 日历关闭按钮
  onClose1() {
    this.setData({
      "calendarData1.show": false,
      "hideCanvas": false
    })
  },
  // 训练数据 - 切换日期范围
  changeMonth(e){
    const { id } = e.target.dataset
    this.setData({
      monthActive: id,
    });
  },
  // 训练数据 - 基础数据 
  async getbasicInformationLast(date) {
    const basicInformationRes = await basicInformationLastApi({
      coachId: store.state.coachId,
      factoryNo: store.state.mac,
      trainDate: date,
    })
    if(basicInformationRes.data == null) {
      this.setData({
        baseData: {
          trainTime: '-',
          heartRateAverage: '-',
          peakHeartRate: '-',
          anaerobic: '-',
          calorie: '-'
        }
      })
      return
    }
    let {trainTime = '-', heartRateAverage='-', peakHeartRate='-', anaerobic='-', calorie='-'} = basicInformationRes.data
    this.setData({
      baseData: {
        trainTime,
        heartRateAverage,
        peakHeartRate,
        anaerobic,
        calorie: parseInt(calorie)
      }
    })
  },
  // 训练数据 - 获取心率区间分布接口
  async getHeartRateCharts(date) {
    const res = await studentMHRLastApi({
      coachId: store.state.coachId,
      factoryNo: store.state.mac,
      trainDate: date
    })
    if (Array.isArray(res.series) && Array.isArray(res.xAxis)) {
      const total = res.series.reduce((a, b) => a + b, 0) || 1;
      const  dataSource = this.data.dataSource.map((item, idx) => {
        return {
          ...item,
          value: res.series.length ? res.series[idx] : 0,
          percent: res.series.length ? ((res.series[idx] / total) * 100).toFixed() : 0,
          time: res.xAxis.length ? (res.xAxis[idx] && res.xAxis[idx].slice(0, 8)) : "00:00",
        };
      });
      this.setData({
        dataSource
      })
    }
  },
  // 获取分段心率
  async getHeartRate(date) {
    const heartRateRes = await queryPage2Api({
      coachId: store.state.coachId,
      factoryNo: store.state.mac,
      trainDate: date
      // trainDate: '2025-11-10'
    })
    if(heartRateRes.code == 0) {
      if(!heartRateRes.data || !heartRateRes.data.list.length) {
        this.setData({
          segmentedHeartRate: [{
            "heartrateValue": '',
            "startTime": "2025-02-04 15:55:00",
            "remark": ''
          },{
            "heartrateValue": '',
            "startTime": "2025-02-04 15:55:00",
            "remark": ''
          },{
            "heartrateValue": '',
            "startTime": "2025-02-04 15:55:00",
            "remark": ''
          },{
            "heartrateValue": '',
            "startTime": "2025-02-04 15:55:00",
            "remark": ''
          },{
            "heartrateValue": '',
            "startTime": "2025-02-04 15:55:00",
            "remark": ''
          },{
            "heartrateValue": '',
            "startTime": "2025-02-04 15:55:00",
            "remark": ''
          }]
        })
        return
      }
      // const rateList = heartRateRes.data
      this.setData({
        segmentedHeartRate: heartRateRes.data.list
      })
    }
  },
  // 训练数据 - 获取训练记录
  async getTrainRecords() {
    const queryOneRes = await queryOneApi({
      coachId: store.state.coachId,
      factoryNo: store.state.mac,
      pageNum: 1,
      pageSize: 5
    })
    queryOneRes.data.map((item) => {
      item.calorie = parseInt(Number(item.calorie || 0))
    })
    this.setData({
      tableData: queryOneRes.data || [],
      titleData: [
        {startTime:'训练日期'},
        {heartRateAverage: '平均心率'},
        {peakHeartRate: '巅峰心率'},
        {anaerobic:'无氧阀值'},
        {heartRate10: '10s心率'},
        {calorie: '卡路里'}
      ]
    })
  },
  /**
   *    体征事件
   */
  // 体征数据 - 体征记录按钮事件
  goTrainRecords2() {
    this.setData({ dialogShow2: true });
  },
  // 体征数据 - 体征记录关闭按钮事件
  onClose2() {
    this.setData({ dialogShow2: false });
  },
  // 体征数据 - 日期选择
  onDateChange2(e) {
    this.setData({
      "calendarData2.show": false,
      "calendarData2.date": e.detail.date
    })
    // 重新获取体征数据
    this.getPhysicalData(e.detail.date)
  },
  // 体征数据 - 日期按钮事件
  changetime2() {
    this.setData({
      "calendarData2.show": true
    })
  },
  // 体征数据 - 日历关闭
  onClose3() {
    this.setData({
      "calendarData2.show": false
    })
  },
  // 体征数据 - 获取体征数据
  async getPhysicalData(date) {
    try {
      const physicalRes = await signApi({
        studentId: store.state.studentId,
        date
      });
      this.setData({
        physical: physicalRes
      })
    } catch (err) {
      console.error('getPhysicalData执行出错：', err); // 捕获所有可能的错误
    }
  },
  // 体征数据 - 获取体征的图表数据
  async getqueryPage() {
    const queryPageRes = await queryPageSortApi()
    if(queryPageRes.code == 0) {
      this.setData({
        options: queryPageRes.data
      })
    }
  },
  // 体征数据 - 获取体征记录
  async getquerySignRecord() {
    const signRecordRes = await querySignRecordApi({
      supervisorId: store.state.studentId,
      pageNum: 1,
      pageSize: 7
    })
    if(signRecordRes.code == 0) {
      this.setData({
        tableData2: signRecordRes.data
      })
    }
  },
  /**
   *  其他
   */
  // tab 切换事件
  onChange(event) {
    // if(event.detail.name == '1') {
    //   this.updateChart()
    // }
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  onAddTodo(e) {
  },
  // 手动更新训练数据下面的图表
  updateChart() {
    // 更新图表数据示例
    const newData = {
      data: [9, 95, 91, 95, 92, 92, 93, 96, 94, 96, 94, 95, 93]
    };
    // 通过id获取组件实例并调用更新方法
    this.selectComponent('#myEchartsLine2').updateChartData(newData);
  },
  // 综合数据 - 体征数据点击事件
  handleOptionClick(e) {
    const optionId = e.currentTarget.dataset.id;
    const { selectType, maxSelect } = this.data;
    const { options } = this.data;
    let updatedOptions = [...options];
    let selectedCount = 0;
    let targetOption = null;

    updatedOptions.forEach((group, groupIndex) => {
      group.indicators.forEach((item, itemIndex) => {
        if (item.selected) selectedCount++;
        if (item.indicatorId === optionId) {
          targetOption = { groupIndex, itemIndex, ...item };
        }
      });
    });

    if (!targetOption) return;
  
    if (selectType === 'single') {
      updatedOptions = updatedOptions.map((group, groupIndex) => ({
        ...group,
        indicators: group.indicators.map((item, itemIndex) => ({
          ...item,
          selected: groupIndex === targetOption.groupIndex && itemIndex === targetOption.itemIndex
        }))
      }));
    } else {
      if (targetOption.selected) {
        // 取消选择
        updatedOptions[targetOption.groupIndex].indicators[targetOption.itemIndex].selected = false;
      } else if (selectedCount < maxSelect) {
        // 新增选择（未超过最大选择数）
        updatedOptions[targetOption.groupIndex].indicators[targetOption.itemIndex].selected = true;
      } else {
        wx.showToast({
          title: `最多只能选择${maxSelect}项`,
          icon: 'none'
        });
        return;
      }
    }
    
    this.setData({
      options: updatedOptions
    });
    this.calculateGroupSelectedCounts();
  },
  // 计算每个分组的选中项数量
  calculateGroupSelectedCounts() {
    const { options } = this.data;
    const counts = options.map(group => {
      if (!Array.isArray(group.indicators)) return 0;
      return group.indicators.filter(item => item.selected).length;
    });
    this.setData({ groupSelectedCounts: counts });
  },
  // 综合数据 - 提交选择结果
  submitSelection() {
    const { options: groups } = this.data;
    // 用于存储所有选中项的信息
    const selectedOptions = [];
  
    // 遍历外层的分组 (groups)
    groups.forEach(group => {
      // 遍历每个分组下的指标 (indicators)
      if (Array.isArray(group.indicators)) {
        group.indicators.forEach(indicator => {
          // 如果指标被选中，则将其添加到 selectedOptions 数组中
          if (indicator.selected) {
            selectedOptions.push(indicator);
          }
        });
      }
    });
  
    // 从选中的选项中提取名称和 ID
    const resultArr = selectedOptions.map(item => item.indicatorName);
    const result = resultArr.join('、');
    const ids = selectedOptions.map(item => item.indicatorId);
  
    // 显示模态框
    wx.showModal({
      title: '选择结果',
      content: `您选择了：${result || '未选择任何选项'}`,
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          // 获取图表数据
          this.setData({
            ids: ids,
            linesHideCanvas: false
          });
        }
      }
    });
  
    // 如果没有选择任何选项，则直接返回
    if (!result) return;
  },
  /**
   * 最好成绩
   */
  async getBestResult() {
    const bastRes =await bestResultApi({
      studentId: store.state.studentId,
      pageNum: 1,
      pageSize: 5
    })
    if(bastRes.code == 0) {
      const bastList = bastRes.data
      this.setData({
        scoreList: bastList
      })
    }
  },
  onLoad() {
    const tabBarIndex = app.globalData.tabBarIndex;
    this.setData({
      active: tabBarIndex
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    let that  = this
    // setTimeout(() => {
    //   initChart(that, that.data.today);
    // }, 100); 
    // initChart(this, this.data.today)
    wx.createSelectorQuery()
      .select('.tab-container')
      .boundingClientRect(rect => {
        if (rect) {
          this.setData({
            "chartWidth": rect.width
          })
        }
      })
      .exec()
    // 初始化日期
    let date = this.formatDate(new Date())
    this.setData({
      "calendarData1.date": date,
      "calendarData2.date": date
    })
    // 体征数据 - 获取体征数据
    this.getPhysicalData(date)
    // 体征数据 - 获取体征的图表数据
    this.getqueryPage()
    // 体征数据 - 获取体征记录
    this.getquerySignRecord()
    // 训练数据 - 获取训练基础数据
    this.getbasicInformationLast(date)
    // 训练数据 - 获取分段心率
    this.getHeartRate(date)
    // 训练数据 - 获取心率区间分布接口
    this.getHeartRateCharts(date)
    // 训练数据 - 心率曲线
    // this.getHeartRateCurveCharts(date)
    // 训练数据 - 获取训练记录
    this.getTrainRecords() 
    // 获取最好成绩
    this.getBestResult()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})